# -*- coding: utf-8 -*-
# vim:et:sw=4:sts=4:ai:nosi
# Copyright (c) 2012 Flibusta Quotes Team
#
# This file is part of Flibusta Quotes.
#
# Flibusta Quotes is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

import webapp2
from google.appengine.api import users, memcache
from model import Quote
from base import BaseHandler
from quotes import QuotesHandler
from author import AuthorHandler

from config import MAX_QUOTE_LENGTH


class AddQuoteHandler(BaseHandler):
    post_params = [
        ('author', 'unicode'),
        ('content', 'unicode'),
        ('source', 'unicode')]
    memcache_key = 'addquote'

    @BaseHandler.simple_get_method
    def get(self):
        """Add quote form"""
        # Return template name to render
        return 'add.html'

    @BaseHandler.post_method
    def post(self, author, content, source):
        """Add a quote"""
        # Check for errors in the form data
        errors = []
        if not content or content.strip() == '':
            # Quote cannot be empty
            errors.append('Цитата не может быть пустой')
        else:
            if len(content) > MAX_QUOTE_LENGTH:
                # Quote cannot be longer than MAX_QUOTE_LENGTH characters
                errors.append('Цитата слишком большая. Максимальная длина - %d символов' %
                              MAX_QUOTE_LENGTH)
            if content.find('http://') != -1:
                # There must be no http links in the quote
                errors.append('Ссылки в цитате недопустимы')
        if not author or author.strip() == '':
            # Quote author must be specified
            errors.append('Автор не указан')
        if not source:
            # Source link must be specified
            errors.append('Источник не указан')
        else:
            if not (source.startswith('http://flibusta.net/') or
                    source.startswith('http://lib.rus.ec/')):
                if source.startswith('http://proxy.flibusta.net/'):
                    source = source.replace('proxy.', '', 1)
                elif source.startswith('http://www.flibusta.net/'):
                    source = source.replace('www.', '', 1)
                else:
                    # Source link must start with http://flibusta.net/
                    errors.append('Ссылка на источник должна начинаться с http://flibusta.net/')
        if errors:
            # There were errors, show them to the user
            return 'add.html', { 'errors': errors, 'request': self.request, 'memcache_key': None }

        # Get current user
        user = users.get_current_user()

        # Put quote to the datastore
        quote = Quote()
        quote.author = author
        quote.content = content.strip('\r\n')
        quote.source = source
        if user:
            quote.submitter = user
        quote.put()

        # Remove stale pages from the cache
        memcache.delete(QuotesHandler._get_key())
        memcache.delete(AuthorHandler._get_key(author=author))

        # Return redirect url
        return '/'

